<template>
  <div class="menu-tab-div-body">
    <!-- <div style="border:1px solid green;height:100px;margin:20px 50px;"> -->
    <div class="h-24 mt-5 my-12">
      <el-divider></el-divider>
      <el-row :gutter="20" class="mt-20">
        <el-col :span="18" :offset="2">
          <div class="grid-content bg-purple">
            <span style="font-size:18px;color:#1f2f3d;font-weight: 700;">发送账号：</span>
            <el-cascader
              :options="listOfAuthorizedMailbox"
              :props="cascaderProps"
              v-model="form.Addresser"
              collapse-tags
              class="sm:w-96 md:w-3/4"
              @change="changeAddresserLable"
              clearable></el-cascader>
            <div class="inline-block text-3xl">
              <slot v-if="isChecked">
                <i class="el-icon-success" style="color:green;position: relative; top: 6px;" />
              </slot>
              <slot v-else>
                <i class="el-icon-error" style="color:red;position: relative; left: 5px;top: 6px;" />
              </slot>
            </div>
            <!-- <el-button style="margin-left:10px;" @click="">分组管理</el-button> -->
            <!-- <el-button style="margin-left:10px;" >账号管理</el-button> -->
          </div>
          <div class="text-center px-3 py-10">
            <el-row>
              <el-col :span="16" :offset="5">
                <div class="flex flex-wrap">
                  <div>
                    <el-button class="ml-1 float-left" size="mini" type="success" @click="handleShowAddEmailAccount(true)">新增授权账号</el-button>
                    <el-button class="ml-1 float-left" size="mini" type="success" @click="handleManageGroup()">分组管理</el-button>
                    <el-button class="ml-1 float-left" size="mini" type="success" @click="handleManageAccount()">账号管理</el-button>
                  </div>
                  <div>
                    <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
                  </div>
                </div>
                <el-table
                  :data="form.AddresserLabel.filter(data => !searchAddresser || data.toLowerCase().includes(searchAddresser.toLowerCase()))"
                  style="width: 100%;"
                  max-height="550"
                >
                  <!-- <el-table-column label="发件箱" align="center">
                    <template slot-scope="scope">
                    {{ scope.row }}
                    </template>
                  </el-table-column> -->

                  <el-table-column
                    align="center">
                    <template slot="header">
<!--                     TODO 无法输入-->
<!--                      <el-input-->
<!--                        v-model="searchAddresser"-->
<!--                        size="mini"-->
<!--                        clearable-->
<!--                        placeholder="输入邮箱搜索"/>-->
                    </template>
                    <template slot-scope="scope">
                      {{ scope.row }}
                    </template>
                    <!-- <template slot-scope="scope">
                      <el-button
                        size="mini"
                        plain
                        @click="handleEmailRemove(scope.row)">移除</el-button>
                    </template> -->
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>

          </div>
        </el-col>
        <el-col :span="6" :offset="6"><div class="grid-content bg-purple"></div></el-col>
      </el-row>
      <!-- <el-divider></el-divider> -->
    </div>
    <div style="height:40%;margin:120px 50px;" v-show="this.showAddEmailAccountVisible">
      <el-row :gutter="20">
        <el-col :span="18" :offset="6">
          <p style="font-weight:400;color:#1f2f3d;font-size:20px;float:left;display:block;margin-left: 9px;">新增邮箱授权</p>
        </el-col>
        <el-col :span="18" :offset="6">
          <el-form ref="emailForm" :model="emailForm" :rules="emailFormRules" label-width="100px" style="width:600px;text-align:center;border:1px solid grey;border-radius:10px;padding:30px;margin:10px;">
            <el-form-item label="邮箱类型:" prop="emailType">
              <el-select v-model="emailForm.emailType" placeholder="请选择邮箱类型" style="width:100%;">
                <slot v-for="item in emailTypeOptions">
                  <el-option :label="item.label" :value="item.value"></el-option>
                </slot>
              </el-select>
            </el-form-item>
            <el-form-item label="协议:" prop="Driver" v-if="emailForm.emailType===0" :rules="driverRules.Driver">
              <el-select v-model="emailForm.Driver" placeholder="请选择协议" style="width:100%;">
                <slot v-for="item in emailServerTypeOptions">
                  <el-option :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                </slot>
              </el-select>
            </el-form-item>
            <el-form-item label="域名:" prop="Host" v-if="emailForm.emailType===0" :rules="hostRules.Host">
              <el-input v-model="emailForm.Host"></el-input>
            </el-form-item>
            <el-form-item label="端口:" type="number" prop="Port" v-if="emailForm.emailType===0" :rules="portRules.Port">
              <el-input v-model="emailForm.Port"></el-input>
            </el-form-item>
            <el-form-item label="邮箱地址:" prop="emailAddress">
              <el-input v-model="emailForm.emailAddress"></el-input>
            </el-form-item>
            <el-form-item label="密钥/令牌:" prop="secret">
              <el-input v-model="emailForm.secret"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="success" plain @click="submitForTesting('emailForm')">提交检测</el-button>
              <el-button>取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <manage-account :show.sync="showManageAccountVisible"/>
    <manage-group :show.sync="showManageGroupVisible"/>
  </div>
</template>

<script>
import { validateEmail } from '@/utils/validate'
import { getAction, postAction } from '@/api/common'
import ManageAccount from '../manageAccount.vue'
import ManageGroup from '../manageGroup.vue'
import UploadExcel from '@/components/UploadExcel/index.vue'
export default {
  name: 'senderAccount',
  components: {
    UploadExcel,
    ManageAccount,
    ManageGroup
  },
  props: {
    addresser: {
      type: Array,
      default: () => []
    },
    addresserLabel: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      cascaderProps: { multiple: true, emitPath: false, value: 'value', label: 'label' },
      /// //////////////////////////发送账号//////////////////////////////////
      isChecked: false,
      emailForm: {
        Driver: null,
        Host: null,
        Port: null,
        emailType: null,
        emailAddress: '',
        secret: ''
      },
      sendAccountOptions:
        [
          { value: '三全鲜食（北新泾店）', address: '长宁区新渔路144号' },
          { value: 'Hot honey 首尔炸鸡（仙霞路）', address: '上海市长宁区淞虹路661号' },
          { value: '新旺角茶餐厅', address: '上海市普陀区真北路988号创邑金沙谷6号楼113' }
        ],
      emailTypeOptions:
        [
          { key: '0', label: '其他邮箱', value: '0' },
          { key: '1', label: 'QQ邮箱', value: '1' },
          { key: '2', label: '163邮箱', value: '2' },
          { key: '3', label: '126邮箱', value: '3' },
          { key: '4', label: '新浪邮箱', value: '4' },
          { key: '5', label: '搜狐邮箱', value: '5' },
          { key: '6', label: '谷歌邮箱', value: '6' },
          { key: '7', label: 'OutLook邮箱', value: '7' }
        ],
      emailServerTypeOptions:
        [
          { key: '0', label: 'SMTP', value: 'SMTP', disabled: false },
          { key: '1', label: 'IMAP', value: 'IMAP', disabled: true },
          { key: '2', label: 'POP3', value: 'POP3', disabled: true },
          { key: '3', label: 'Exchange', value: 'Exchange', disabled: true },
          { key: '4', label: 'CardDAV', value: 'CardDAV', disabled: true },
          { key: '5', label: 'CalDAV', value: 'CalDAV', disabled: true }
        ],
      emailFormRules: {
        emailType: [
          { required: true, message: '请选择邮箱类型', trigger: 'change' }
        ],
        emailAddress: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' },
          { min: 3, max: 320, message: '长度在 3 到 320 个字符', trigger: 'blur' }// 64 + @ + 255 //x@y
        ],
        secret: [
          { required: true, message: '请输入密钥/令牌', trigger: 'blur' },
          { min: 6, max: 32, message: '长度在 6 到 32 个字符', trigger: 'blur' }
        ]
      },
      driverRules: {
        Driver: [
          { required: true, message: '请选择协议', trigger: 'change' }
        ]
      },
      hostRules: {
        Host: [
          { required: true, message: '请输入域名', trigger: 'blur' }
        ]
      },
      portRules: {
        Port: [
          { required: true, message: '请输入端口号', trigger: 'blur' }
        ]
      },
      showManageAccountVisible: false,
      showManageGroupVisible: false,
      showAddEmailAccountVisible: false,
      listOfAuthorizedMailboxArray: [],
      listOfAuthorizedMailbox: [],
      form: {
        Addresser: this.addresser,
        AddresserLabel: this.addresserLabel
      },
      searchAddresser: ''
    }
  },
  created() {
    this.init()
  },
  inject: ['showProgressDialog'],
  methods: {
    init() {
      getAction({}, 'EmailSendFree/GetInit')
        .then((res) => {
          this.listOfAuthorizedMailbox = res.data.listOfAuthorizedMailbox
          this.listOfAuthorizedMailbox.forEach(m => {
            m.children?.forEach(c => { this.listOfAuthorizedMailboxArray[c.value] = c.label })
          })
        })
    },
    handleSelect() {
      console.log('处理选中变化', this.form.Addresser)
      if (this.form.Addresser.length > 0) {
        this.isChecked = true
      } else {
        this.isChecked = false
      }
      // TODO: 消除验证
      this.emailForm = {
        emailType: null,
        emailAddress: '',
        secret: ''
      }
    },
    handleClear() {
      this.form.Addresser = null
      this.isChecked = false
    },
    /// //////////////////////////发送账号//////////////////////////////////
    submitForTesting(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 验证的值没有过滤，需要过滤的话得加逻辑，问题不大，传到服务端并不作处理
          postAction(this.emailForm, 'EmailConfig/ConfigAddressee')
            .then((res) => {
              console.log(res)
              if (res.code === 20000) {
                this.$message({
                  message: '邮箱授权成功!',
                  type: 'success'
                })
                this.init()
              } else {
                this.$message({
                  message: res.message ?? '邮箱授权失败!',
                  type: 'warning'
                })
              }
              this.resetForm('emailForm')
            })
        } else {
          this.$message({
            message: '请检查授权参数!',
            type: 'warning'
          })
          return false
        }
      })
    },
    handleManageAccount() {
      this.showManageAccountVisible = true
    },
    handleManageGroup() {
      this.showManageGroupVisible = true
    },
    handleShowAddEmailAccount(val) {
      if (this.showAddEmailAccountVisible) {
        this.showAddEmailAccountVisible = false
      } else {
        this.showAddEmailAccountVisible = true
      }
    },
    changeAddresserLable(val) {
      this.form.AddresserLabel = val?.map(m => this.listOfAuthorizedMailboxArray[m]) ?? []
      this.$emit('update:addresser', val)
      this.$emit('update:addresserLabel', this.form.AddresserLabel)
      this.handleSelect()
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message.warning('最大上传1M')
      return false
    },

    handleSuccess({ results, header }) {
      const data = results.map(r => ({
        emailAddress: r['邮箱地址'],
        emailType: this.getEmailType(r['邮箱地址']),
        secret: r['密钥/令牌'],
        Driver: null,
        Host: null,
        Port: null
      }))
      console.log(data)
      postAction(data, 'EmailConfig/BatchConfigAddressee')
        .then((res) => {
          if (res.code === 20000) {
            this.$message({
              message: '邮箱授权成功!',
              type: 'success'
            })
            this.init()
          } else {
            this.$message({
              message: res.message ?? '邮箱授权失败!',
              type: 'warning'
            })
          }
          this.resetForm('emailForm')
        })
    },
    getEmailType(email) {
      const types = {
        'qq.com': 1,
        '126.com': 2,
        '163.com': 3,
        'sina.com': 4,
        'sohu.com': 5,
        'gmail.com': 6,
        'live.com': 7
      }
      return types[email.split('@')[1]] ?? 0
    }
  }
}
</script>

<style scoped>

</style>
